package br.com.foxinline.servlet;

import br.com.foxinline.modelo.Anexo;
import br.com.foxinline.servico.AnexoServico;
import br.com.foxinline.util.ArquivoUtilitario;
import java.io.IOException;
import java.io.OutputStream;
import java.nio.file.Files;
import java.nio.file.Paths;
import javax.ejb.EJB;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 *
 * @author laverson
 */
@WebServlet(name = "ImagemPadraoServlet", urlPatterns = "/show/*")
public class ImagemPadraoServlet extends HttpServlet {

    @EJB
    AnexoServico anexoService;
    public static final String APPLICATION_PDF = "application/pdf";
    private static final String IMG_PADRAO = "/media/images/fox-avatar.png";
    private static final String PNG = ".png";
    private static final long serialVersionUID = 201011231103L;
    private ArquivoUtilitario arquivoUtilitario;

    public ImagemPadraoServlet() {
        super();
        arquivoUtilitario = new ArquivoUtilitario();
    }

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        OutputStream out = null;
        try {
            String idPdf = request.getParameter("id");
            String pdf = request.getParameter("pdf");
            String img = request.getParameter("img");

            if (idPdf != null) {
                Anexo anexo = anexoService.find(Long.parseLong(idPdf));

                //@todo Deve ser removido após criar método para excluir arquivos remanecentes na tabela anexo
                if ((anexo.getContent() != null || anexo.getArquivo() != null) && anexo.getUrl() != null) {
                    arquivoUtilitario.gravarAnexo(anexo, anexo.getUrl());
                    anexo.setContent(null);
                    anexo.setArquivo(null);
                    anexoService.update(anexo);
                }

                out = response.getOutputStream();
                response.setContentType(APPLICATION_PDF);

                String caminho = removerAcentos(anexo.getNome());
                caminho = anexo.getUrl() + caminho;
                response.getOutputStream().write(Files.readAllBytes(Paths.get(caminho)));
            } else if (pdf != null) {
                out = response.getOutputStream();
                response.setContentType(APPLICATION_PDF);
                response.getOutputStream().write(Files.readAllBytes(Paths.get(ArquivoUtilitario.REAL_PATH_TMP + removerAcentos(pdf))));
            } else if (img != null) {
                out = response.getOutputStream();
                response.setContentType(PNG);
                response.getOutputStream().write(Files.readAllBytes(Paths.get(request.getServletContext().getRealPath(IMG_PADRAO))));
            }
            if (out != null) {
                out.close();
            }
        } catch (Exception e) {
            System.err.println(e);
        }
    }

    public String removerAcentos(String url) {
        url = url.replaceAll("[ãâàáä]", "?")
                .replaceAll("[êèéë]", "?")
                .replaceAll("[îìíï]", "?")
                .replaceAll("[õôòóö]", "?")
                .replaceAll("[ûúùü]", "?")
                .replaceAll("[ÃÂÀÁÄ]", "?")
                .replaceAll("[ÊÈÉË]", "?")
                .replaceAll("[ÎÌÍÏ]", "?")
                .replaceAll("[ÕÔÒÓÖ]", "?")
                .replaceAll("[ÛÙÚÜ]", "?")
                .replace('ç', '?')
                .replace('Ç', '?')
                .replace("[ñǹń]", "?")
                .replace("[ÑŃǸ]", "?");
        return url;
    }
}
